<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>时间计算</title>
    <script>
        function riqicha() {
            let kaishi = document.getElementById("kaishiriqi").value;//字符串类型“2024-11-20”
            kaishi = new Date(kaishi);//日期类型
            let jiezhi = document.getElementById("jiejriqi").value;//字符串类型“2024-11-25”
            jiezhi = new Date(jiezhi);//日期类型
            kaishi = kaishi.getTime();//开始日期毫秒数，1970-01-01 00:00:00 UTC+00:00
            jiezhi = jiezhi.getTime();//结束日期毫秒数，1970-01-01 00:00:00 UTC+00:00
            let cha = (jiezhi - kaishi) / (24 * 3600 * 1000); //相差天数
            document.querySelector("#chax").innerHTML = cha//显示相差天数

        }

        function qianhou() {
            let riqi = document.querySelector("#riqi").value;//获取日期
            riqi = new Date(riqi);//将日期字符串转换为日期对象
            let tianshu = document.querySelector("#qianhou").value;//获取天数
            let zhiding = ""
            tianshu = Math.round(tianshu);//取整 -2

            if (tianshu < 0) {
                let qian = newDate(riqi.getTime() - Math.abs(tianshu) * 24 * 3600 * 1000) //前日期 2024-11-18
                //计算日期是星期几
                let week = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
                let day = week[qian.getDay()]
                zhiding = qian.toLocaleDateString() + " " + day//格式化日期


            } else if (tianshu > 0) {
                let hou = new Date(riqi.getTime() + tianshu * 24 * 3600 * 1000) //后日期 2024-11-28
                //计算前日期是星期几
                let week = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
                let day = week[hou.getDay()]
                zhiding = hou.toLocaleDateString() + " " + day//格式化日期

            } else {
                zhiding = "同一天"
            }
            document.querySelector("#zhiding").innerHTML = zhiding//显示计算结果
        }

    </script>
</head>

<body>
    <H1>计算时间差</H1>
    开始日期：<input type="date" id="kaishiriqi"><br>
    结束日期：<input type="date" id="jiejriqi"><br>
    相差<span id="chax">0</span>天
    <button onclick="riqicha()">计算时间差</button>
    <br>

    日期：<input type="date" id="riqi">
    <br>
    相差
    <input type="text" id="qianhou">天
    <br>
    是：<span id="zhiding">0</span>
    <button onclick="qianhou()">计算前后日期</button>


</body>

</html>